package com.mef.smsplat.eterm;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import com.hc24.util.DateUtil;
import com.mef.smsplat.eterm.bean.DetrItem;
import com.mef.smsplat.eterm.bean.DetrItemSeg;
import com.mef.smsplat.eterm.bean.DetrResult;
import com.mef.smsplat.eterm.bean.DetrSegment;

/**
 * Detr工具
 * @author hc24
 *
 */
public class DetrUtil {
	
	/**
	 * 解析detr后返回的结果
	 * @param detrAllResult
	 * @return
	 */
	public static DetrResult parseDetr(String content){
		//String content=detrAllResult.getContent();
		DetrResult detrResult=new DetrResult();
		String airCompany= content.substring(content.indexOf("ISSUED BY: ")+11, content.indexOf(" ORG/DST:")).trim();//航空公司
		int od=content.indexOf("ORG/DST: ");
		String org_dst[]=content.substring(od+9, od+17).split("/");
		String org=org_dst[0];//出发城市
		String dst=org_dst[1];//到达城市
		String passengerName=content.substring(content.indexOf("PASSENGER: ")+11,content.indexOf("EXCH:"));
		passengerName=passengerName.replaceAll(" ", "").replaceAll("\n", "").replaceAll("\r", "");//旅客姓名
		int rl=content.indexOf("RL:");
		String allPnr =content.substring(rl+3,content.indexOf("TO:"));//cpnr&bpnr
		String[] pnrs=allPnr.split("/");
		String pnr=pnrs[0].replaceAll(" ", "").replaceAll("\n", "").replaceAll("\r", "");
		String cpnr="";
		if(pnrs.length>1){
			cpnr=StringUtils.trimToEmpty(pnrs[1].replaceAll(" ", "").replaceAll("\n", "").replaceAll("\r", ""));;
		}
		if(StringUtils.isNotEmpty(cpnr)&&cpnr.length()>6){
			cpnr=cpnr.substring(0,6);
		}else{
			cpnr="";
		}		
		String fare ="";
		if(content.indexOf("CNY ")>-1){
			content.substring(content.indexOf("CNY ")+4, content.indexOf("|"));//票面价
		}
		String taxCn ="";
		if(content.indexOf("TAX:")>-1 && content.indexOf("CN|")>-1){
			taxCn=content.substring(content.indexOf("TAX:"), content.indexOf("CN|"));
		}
		String cn= "";
		if(taxCn.indexOf("CNY")>-1){
			cn = taxCn.substring(taxCn.indexOf("CNY")+3).replace(" ","");//机场建设费
		}
		
		String taxYq ="";
		if(content.indexOf("TAX:")>-1 && content.indexOf("YQ|")>-1){
			taxYq=content.substring(content.lastIndexOf("TAX:"), content.indexOf("YQ|"));
		}
		String yq ="";
		if(taxYq.indexOf("CNY")>-1){
			 yq=taxYq.substring(taxYq.indexOf("CNY")+3).replace(" ", "");
		}
		
		String totalStr=content.substring(content.indexOf("TOTAL:"));
		String total=totalStr.substring(totalStr.indexOf("CNY ")+4,totalStr.indexOf("|"));
		
//		if(detrAllResult.getParameter().toUpperCase().indexOf("TN")>-1){
//			detrResult.setTicketNo(detrAllResult.getParameter().substring(3));
//		}else{
		//查找票号
			String tkt = content.substring(content.indexOf("TKTN: "));
			if(tkt.length()>5){
				tkt =StringUtils.trimToEmpty(tkt.split(":")[1]).replace("\n", "").replaceAll(" ", "");
				if(tkt.lastIndexOf("-")>5){
					tkt = tkt.substring(0,tkt.lastIndexOf("-"));
				}
				detrResult.setTicketNo(tkt);
			}
//		}
		detrResult.setAirCompany(airCompany);
		detrResult.setOrgCity(org);
		detrResult.setDesCity(dst);
		detrResult.setPassengerName(passengerName);
		detrResult.setAirCompanyPnr(pnr);
		detrResult.setAgentPnr(cpnr);
		try{
		detrResult.setTicketPrice(fare==""?0:Float.parseFloat(fare));
		detrResult.setTotal(total==""?0:Float.parseFloat(total));
		detrResult.setFuelFee(yq==""?0:Float.parseFloat(yq));
		detrResult.setAirPortFee(cn==""?0:Float.parseFloat(cn));
		}catch(NumberFormatException e){
			e.printStackTrace();
		}
		
		String strSeg=content.substring(content.indexOf("O FM:"), content.indexOf("FC:M")).trim();
		String[] segs=  strSeg.split("\r");
		List<String> segList=new ArrayList<String>();
		for(int i=0;i<segs.length;i++){
			if(segs[i].contains("FM:")||segs[i].contains("TO:"))
				segList.add(segs[i]);
		}
		List<DetrSegment> segsList=new ArrayList<DetrSegment>();
		for(int i=0;i<segList.size()-1;i++){
			DetrSegment seg=new DetrSegment();
			String orgCity=segList.get(i).substring(6,9);//出发城市
			String dstCity=(segList.get(i+1)+" ").substring(6,9);//到达城市
			String[] temps= segList.get(i).split(" ");//切割
			List<String> strList=new ArrayList<String>();
			for(int m=0;m<temps.length;m++){
				if(!temps[m].equals(""))
					strList.add(temps[m]);
			}
			
			String segStatus =null;
			for(String status: strList){
				if(status.indexOf("OPEN")>-1){
					segStatus =status;
					break;
				}else if(status.indexOf("USED")>-1||status.indexOf("FLOWN")>-1){
					segStatus = status;
					break;
				}else if(status.indexOf("VOID")>-1){
					segStatus = status;
					break;
				}
			}
			if(StringUtils.isEmpty(segStatus)){
				segStatus= strList.get(10);
			}
			seg.setSegStatus(segStatus);
			if(seg.getSegStatus().indexOf("VOID")>-1){
				continue;
			}
			
			String flightNo=strList.get(2);
			//O FM:1SHA MU FM 9469  Q 30NOV 1730 OK SUPQ07                   20K USED/FLOWN 
			//O FM:1CTU CA     421  G 05JAN 1300 OK G/CA4Z1234  
			//O FM:1CTU MU KN 8029  X 07FEB 0755 OK YX60       07FEB3/07FEB3 20K OPEN FOR USE           RL:NKV44Y  / 
			int indexX=0;//偏移量,是否是共享航班
			if(strList.get(3).length()==2){
				flightNo+=strList.get(3);
				indexX=1;
			}
			flightNo = flightNo+strList.get(3+indexX);
			String cabin=strList.get(4+indexX);
			String flightDate=strList.get(5+indexX);
			String flightTime=strList.get(6+indexX);
			
			seg.setCabin(cabin);
			seg.setDst(dstCity);
			seg.setFlightDate(DateUtil.ymd(flightDate));//Eterm日期格式在在接口内部使用，对外都是yyyy-MM-dd格式的字符串
			seg.setFlightNo(flightNo);
			seg.setFlightTime(flightTime);
			seg.setOrg(orgCity);
			seg.setSegSeq(i+1);
			segsList.add(seg);
		}
		detrResult.setDetrSegments(segsList);
		
		return detrResult;
	}
	
	/**
	 * 对于使用NM和NI提取使用此方法<br/>
	 * 由于是循环提取票号耗费时间较长，所以不推荐使用此方法
	 * @param detrAllResult
	 * @return
	 */
	public static List<DetrResult> parseDetr2(String content){
		return parseDetrList(parseTktList(content));
	}
	
	/**
	 * 对于NM和NI提取的结果解析成DetrItem列表
	 * @param detrAllResult
	 * @return
	 */
	public static List<DetrItem> parseDetr3(String content){
		//String content=detrAllResult.getContent();
		List<DetrItem> list=new ArrayList<DetrItem>();
		
		String[] detrs=content.split("DETR:");
		for(int i=2;i<detrs.length;i++){
			DetrItem detrItem=new DetrItem();
			
			String tktNo=detrs[i].substring(detrs[i].indexOf("TN/")+3,detrs[i].indexOf("NAME:")).trim();
			
			String passengerName=detrs[i].substring(detrs[i].indexOf("NAME:")+5,detrs[i].indexOf("\n")).trim();
			String[] segs=detrs[i].split("FOID:");//2-?
			List<DetrItemSeg> detrItemSegs=new ArrayList<DetrItemSeg>();
			for(int j=1;j<segs.length;j++){
				String[] temp=RtUtil.split(segs[j], " ");
				List<String> tempList=new ArrayList<String>();
				for(int m=0;m<temp.length;m++){
					tempList.add(temp[m]);
				}
				String idType=tempList.get(0).substring(0,2);
				String idNo=tempList.get(0).substring(2);
				String flightNo=tempList.get(1);
				String flightDate="";
				String city="";
				String segStatus="";
				int index = 0;//偏移量,航班号为三位时，中间会有空格 CA 421 /05JAN13/CTUPEK
				if(flightNo!=null &&flightNo.length()==2){
					flightNo =StringUtils.trim(flightNo+tempList.get(2)); 
					index++;
				}
				if(flightNo.indexOf("OPEN")>-1||flightNo.indexOf("VOID")>-1){//"CAOPEN /OPEN   /CTUPEK REFU "
					 flightDate = StringUtils.trim(tempList.get(2));
					 city=tempList.get(3+index).substring(tempList.get(3+index).length()-6);
					 if(tempList.size()>(3+index)){//存在位置的客票状态
							segStatus=tempList.get(3+index);
					}
				}else{
					//CA 421 /05JAN13/CTUPEK
					flightDate = tempList.get(2+index).substring(1,tempList.get(2+index).lastIndexOf("/"));
					city=tempList.get(2+index).substring(tempList.get(2+index).length()-6);
					if(tempList.size()>(3+index)){//存在位置的客票状态
						segStatus=tempList.get(3+index);
					}
				}
				
				DetrItemSeg itemSeg=new DetrItemSeg();
				itemSeg.setCity(city);
				itemSeg.setFlightDate(flightDate);
				itemSeg.setFlightNo(flightNo);
				itemSeg.setSegStatus(segStatus);
				detrItemSegs.add(itemSeg);
				
				detrItem.setIdNo(idNo);
				detrItem.setIdType(idType);
			}
			
			detrItem.setTktNo(tktNo);
			detrItem.setPassengerName(passengerName.split(" ")[0]);
			detrItem.setDetrItemSegs(detrItemSegs);
			
			list.add(detrItem);
		}
		return list;
	}
	
	/**
	 * 解析使用NM/xxx和NI/xxx获得的票号
	 * @param detrAllResult
	 * @return
	 */
	private static List<String> parseTktList(String content){
		//String content=detrAllResult.getContent();
		Pattern p=Pattern.compile("DETR:TN/[0-9]{3}-[0-9]{10}");
		Matcher m=p.matcher(content);
		List<String> strTkts=new ArrayList<String>();
		while(m.find()){
			String tkt=m.group();
			strTkts.add(tkt.substring(8));
		}
		return strTkts;
	}
	
	/**
	 * 根据票号得到DetrResult列表
	 * @param strTkts
	 * @return
	 */
	private static List<DetrResult> parseDetrList(List<String> strTkts){
		List<DetrResult> list=new ArrayList<DetrResult>();
		if(strTkts==null||strTkts.size()==0)
			return list;
		//DetrAllRequest detrAllRequest=new DetrAllRequest();
		//detrAllRequest.setUser(new User());
		//DetrAllMarshal detrAllMarshal=new DetrAllMarshal();
		Detr detr=new Detr(new Eterm());
		//对票号循环发送请求
		for(int i=0;i<strTkts.size();i++){
			String cmd="TN/"+strTkts.get(i);		
			System.out.println(cmd);
			//DetrAllResult detrAllResult= detrAllMarshal.unMarshall(detrAllRequest);
			String content=detr.sendCmd(cmd);
			DetrResult detrResult=DetrUtil.parseDetr(content);
			//System.out.println(detrAllResult);
			list.add(detrResult);			
		}
		
		return list;
	}
	
	
	public static void main(String[] args) {
		
		//不卑不亢
//		String str="O FM:1CTU EU    2205  Y 14SEP 0750 OK Y";
//		String[] strs= str.split(" ");
//		for(int i=0;i<strs.length;i++)
//			if(!strs[i].equals(""))
//				System.out.println(strs[i]);
		
		String str="DETR:TN/876-2039842130              NAME:测试一  FOID:NI1231313                          3UOPEN /OPEN   /CTUCAN REFU  DETR:TN/811-2301918432              NAME:你好     FOID:NI1231313                          EU2205 /22SEP12/CTUHGH OPEN ";
		Pattern p=Pattern.compile("DETR:TN/[0-9]{3}-[0-9]{10}");
		Matcher m=p.matcher(str);
		List<String> strTkts=new ArrayList<String>();
		while(m.find()){
			String tkt=m.group();
			System.out.println(tkt);
		}
	}
}
